import os
import requests
from dotenv import load_dotenv

# 加载 .env 文件
load_dotenv()

def check_discord_bot_access(channel_id, bot_token):
    """
    检查 Discord Bot 是否可以访问指定频道
    :param channel_id: 频道 ID
    :param bot_token: Bot 的 Token
    :return: None
    """
    url = f"https://discord.com/api/v10/channels/{channel_id}"

    headers = {
        "Authorization": f"Bot {bot_token}",
        "Content-Type": "application/json"
    }

    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        print("✅ Bot 成功访问频道！")
        print("频道名称:", response.json().get("name", "未知"))
        return True

    except requests.exceptions.HTTPError as e:
        if response.status_code == 403:
            print("🚫 权限被拒绝：可能是以下原因")
            print("1. Bot 未添加进服务器")
            print("2. Bot 缺少访问该频道的权限")
            print("3. 未开启 'Message Content Intent'")
            print("请前往 Discord Developer Portal 检查权限设置")
        else:
            print(f"❌ HTTP 错误 [{response.status_code}]: {str(e)}")
        return False

    except requests.RequestException as e:
        print(f"🌐 网络请求失败: {str(e)}")
        return False


if __name__ == "__main__":
    # 从环境变量获取配置
    DISCORD_BOT_TOKEN = os.getenv("DISCORD_BOT_TOKEN")
    CHANNEL_ID = "1130739053944373358"  # 替换为你要测试的频道 ID

    if not DISCORD_BOT_TOKEN:
        print("❌ 错误：未在 .env 中找到 DISCORD_BOT_TOKEN")
    else:
        print("🔍 正在检查 Bot 权限...")
        success = check_discord_bot_access(CHANNEL_ID, DISCORD_BOT_TOKEN)
        if success:
            print("🎉 Bot 可以正常访问频道")
        else:
            print("❌ Bot 无法访问频道，请按提示检查权限")